package com.pulaien.shop.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pulaien.api.entity.Message;
import com.pulaien.api.service.impl.MessageServiceImpl;
import com.pulaien.common.annotation.Anonymous;
import com.pulaien.common.annotation.Log;
import com.pulaien.common.constant.Constants;
import com.pulaien.common.constant.HttpStatus;
import com.pulaien.common.core.controller.BaseController;
import com.pulaien.common.core.domain.AjaxResult;
import com.pulaien.common.core.domain.entity.SysUser;
import com.pulaien.common.core.domain.model.LoginBody;
import com.pulaien.common.core.domain.model.LoginUser;
import com.pulaien.common.core.domain.model.RegisterBody;
import com.pulaien.common.domain.ResponseCode;
import com.pulaien.common.enums.BusinessType;
import com.pulaien.common.utils.ConstantsUtil;
import com.pulaien.common.utils.MessageUtils;
import com.pulaien.common.utils.SecurityUtils;
import com.pulaien.common.utils.StringUtils;
import com.pulaien.framework.web.service.SysLoginService;
import com.pulaien.framework.web.service.TokenService;
import com.pulaien.system.domain.dto.customersetup.AdminModifyParam;
import com.pulaien.system.mapper.SysUserMapper;
import com.pulaien.system.service.IStorageBillService;
import com.pulaien.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;

/**
 * 用户信息
 *
 * @author pulaien
 */
@RestController
@RequestMapping("/shop/user")
@Api(tags = "商城端用户管理")
public class ShopUserController extends BaseController
{
    @Autowired
    private ISysUserService userService;

    @Autowired
    private SysLoginService loginService;

    @Resource
    private SysUserMapper userMapper;

    @Resource
    private TokenService tokenService;

    @Autowired
    private MessageServiceImpl messageService;

    @Autowired
    private IStorageBillService istorageBillService;


    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @ApiOperation("登录")
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody)
    {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(), loginBody.getUuid(),"1");
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }



    @ApiOperation("注册")
    @PostMapping("/register")
    public AjaxResult register(@RequestBody RegisterBody registerBody)
    {
        String msg = userService.shopRegister(registerBody);
        return StringUtils.isEmpty(msg) ? success() : error(msg);
    }


    /**
     * 账号激活
     * @param code
     * @return
     */
    @ApiOperation("账号激活")
    @GetMapping("/activate")
    public AjaxResult activate(@RequestParam("code") String code)
    {
        String msg = userService.activate(code);
        return StringUtils.isEmpty(msg) ? success() : error(msg);
    }



    @ApiOperation("校验邮箱")
    @GetMapping(value = "/verifyEmail")
    public AjaxResult verifyEmail(@RequestParam("email") String email) {
        return userService.verifyEmail(email);
    }


    @ApiOperation("发送验证码")
    @GetMapping(value = "/sendVerificationCode")
    public AjaxResult sendEmailVerificationCode(@RequestParam("email") String email,@RequestParam("smsType") String smsType) {

        if (org.apache.commons.lang3.StringUtils.isEmpty(email)){
            if(org.apache.commons.lang3.StringUtils.equals(ConstantsUtil.SMS_TYPE_0,smsType)){
                return AjaxResult.error(10048, MessageUtils.getMessage(10048));
            }else{
                SysUser currentUser = SecurityUtils.getLoginUser().getUser();
                if (currentUser!=null){
                    email=currentUser.getEmail();
                }else {
                    return AjaxResult.error(10048, MessageUtils.getMessage(10048));
                }
            }
        }

        return userService.sendEmailVerificationCode(email,smsType);
    }


    @ApiOperation("发送验证码")
    @GetMapping(value = "/h5/sendVerificationCode")
    public AjaxResult sendEmailVerificationCodeH5(@RequestParam("email") String email,@RequestParam("smsType") String smsType) {

        SysUser sysUser = userMapper.selectOne(new QueryWrapper<SysUser>().eq("email",email).eq("del_flag",ConstantsUtil.FLG_NORMAL).last("limit 1"));
        if (sysUser == null){
            return AjaxResult.error(10049 , MessageUtils.getMessage(10049));
        }


        if (org.apache.commons.lang3.StringUtils.isEmpty(email)){
            if(org.apache.commons.lang3.StringUtils.equals(ConstantsUtil.SMS_TYPE_0,smsType)){
                return AjaxResult.error(10048, MessageUtils.getMessage(10048));
            }else{
                SysUser currentUser = SecurityUtils.getLoginUser().getUser();
                if (currentUser!=null){
                    email=currentUser.getEmail();
                }else {
                    return AjaxResult.error(10048, MessageUtils.getMessage(10048));
                }
            }
        }

        return userService.sendEmailVerificationCode(email,smsType);
    }


    @ApiOperation("校验验证码")
    @PostMapping(value = "/verifyCode")
    public AjaxResult verifyCode(@RequestBody AdminModifyParam modifyParam) {
        if (modifyParam.getEmail()==null){
            try{
                SysUser currentUser = SecurityUtils.getLoginUser().getUser();
                if (currentUser!=null){
                    modifyParam.setEmail(currentUser.getEmail());
                }else {
                    return AjaxResult.error(10048, MessageUtils.getMessage(10048));
                }
            }catch (Exception e){
                return AjaxResult.error(10048, MessageUtils.getMessage(10048));
            }
        }
        return userService.verifyCode(modifyParam,false);
    }

    @ApiOperation("重置密码")
    @PostMapping(value = "/resetPassword")
    public AjaxResult resetPassword(@RequestBody AdminModifyParam adminParam) {
        return userService.resetPassword(adminParam, false);
    }


    @Anonymous
    @ApiOperation("重置密码")
    @PostMapping(value = "/h5ResetPassword")
    public AjaxResult h5ResetPassword(@RequestBody AdminModifyParam modifyParam) {

        SysUser sysUser = userMapper.selectOne(new QueryWrapper<SysUser>().eq("email",modifyParam.getEmail()).eq("del_flag",ConstantsUtil.FLG_NORMAL).last("limit 1"));
        if (sysUser == null){
            return AjaxResult.error(10049 , MessageUtils.getMessage(10049));
        }



        if (modifyParam.getEmail()==null){
            try{
                SysUser currentUser = SecurityUtils.getLoginUser().getUser();
                if (currentUser!=null){
                    modifyParam.setEmail(currentUser.getEmail());
                }else {
                    return AjaxResult.error(10048, MessageUtils.getMessage(10048));
                }
            }catch (Exception e){
                return AjaxResult.error(10048, MessageUtils.getMessage(10048));
            }
        }

        AjaxResult ajaxResult = userService.verifyCode(modifyParam, false);

        if(Integer.valueOf(ajaxResult.get("code").toString()) != HttpStatus.SUCCESS) {
            return ajaxResult;
        }

        HashMap<String, String> data = (HashMap<String, String>) ajaxResult.get("data");

        String secretCode = data.get("secretCode");
        modifyParam.setSecretCode(secretCode);
        return userService.resetPassword(modifyParam, false);
    }


    @ApiOperation("获取个人中心统计信息")
    @GetMapping(value = "/getCenterStatistics")
    public AjaxResult getCenterStatistics() {

        AjaxResult centerStatistics = userService.getCenterStatistics();

        //JSONObject data = (JSONObject)centerStatistics.get("data");
        return centerStatistics;
    }


    @ApiOperation("获取个人中心统计信息")
    @GetMapping(value = "/getUnChatRead")
    public AjaxResult getUnChatRead(String chatId, String fromId) {
        List<Message> messages = messageService.unreadList(chatId, fromId);
        return AjaxResult.success(messages.size());
    }



    @ApiOperation("修改密码")
    @PostMapping(value = "/modifyPassword")
    public AjaxResult modifyPassword(@RequestBody AdminModifyParam adminParam) {
        String password = SecurityUtils.getLoginUser().getUser().getPassword();
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (!SecurityUtils.matchesPassword(adminParam.getOldPassword(), password))
        {
            return AjaxResult.error(MessageUtils.getMessage(10144));
        }

        if (!org.apache.commons.lang3.StringUtils.equals(adminParam.getPassword(),adminParam.getConfirmPassword())){
            return AjaxResult.error(ResponseCode.PASSWORD_NOT_EQUAL);
        }

        String reg="^[a-zA-Z0-9]{6,20}$";
        if (!adminParam.getPassword().matches(reg)){
            return AjaxResult.error(ResponseCode.PASSWORD_FORMAT_WRONG);
        }

        /*String secret=stringRedisTemplate.opsForValue().get(ConstantsUtil.SECRET_CODE_PREFIX + adminParam.getEmail());
        if (org.apache.commons.lang3.StringUtils.isEmpty(secret)||!org.apache.commons.lang3.StringUtils.equals(secret,adminParam.getSecretCode())){
            return AjaxResult.error(ResponseCode.INFO_VALID_FAIL);
        }
        stringRedisTemplate.delete(ConstantsUtil.SECRET_CODE_PREFIX + adminParam.getEmail());*/

        /*SysUser sysUser = userMapper.selectOne(new QueryWrapper<SysUser>().eq("email",adminParam.getEmail()).eq("del_flag",ConstantsUtil.FLG_NORMAL).last("limit 1"));
        if (sysUser == null){
            return AjaxResult.error(ResponseCode.INTERNAL_SERVER_ERROR);
        }*/

        SysUser updateSysUser = new SysUser();
        //将密码进行加密操作
        String newPassword = SecurityUtils.encryptPassword(adminParam.getPassword());
        updateSysUser.setUserId(SecurityUtils.getUserId());
        updateSysUser.setPassword(newPassword);
        userMapper.updateById(updateSysUser);

        loginUser.getUser().setPassword(newPassword);
        tokenService.setLoginUser(loginUser);
        return AjaxResult.success();
    }

    @ApiOperation("校验密码")
    @GetMapping(value = "/validPassword")
    public AjaxResult validPassword(@RequestParam("password") String password) {
        String oldPassword = SecurityUtils.getLoginUser().getUser().getPassword();
        if (!SecurityUtils.matchesPassword(password, oldPassword))
        {
            return AjaxResult.error(10145);
        }else{
            return AjaxResult.success();
        }
    }

    /**
     * 头像上传
     */
    @Log(title = "用户头像", businessType = BusinessType.UPDATE)
    @GetMapping("/updateAvatar")
    public AjaxResult updateAvatar(@RequestParam(value = "avatar") String avatar)
    {
        if (StringUtils.isNotEmpty(avatar))
        {
            LoginUser loginUser = getLoginUser();
            SysUser user = new SysUser();
            user.setUserId(loginUser.getUserId());
            user.setAvatar(avatar);
            if (userService.updateByUserId(user))
            {
                AjaxResult ajax = AjaxResult.success();
                ajax.put("imgUrl", avatar);
                // 更新缓存用户头像
                loginUser.getUser().setAvatar(avatar);
                tokenService.setLoginUser(loginUser);
                return ajax;
            }
        }
        return AjaxResult.error(10205);
    }



    @GetMapping("/test")
    public AjaxResult test() {
        istorageBillService.createBill();
        return AjaxResult.success("操作成功");
    }

}
